//login.js
//获取应用实例
var app = getApp();
var httpclient = require('../../utils/httpclient.js')
Page({
  data: {
    remind: '加载中',
    angle: 0,
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    userInfo: {},
    encryptedData: '',
    iv: '',
    openId: '',
    unionId: '',
    nickname: '',
    loginCode: ''
  },
  goToIndex:function(){
    wx.switchTab({
      url: '/pages/home/home',
    });
  },
  onLoad:function(){
    
  },
  onShow:function(){

  },
  onReady: function(){
    var that = this;
    setTimeout(function(){
      that.setData({
        remind: ''
      });
    }, 1000);
    wx.onAccelerometerChange(function(res) {
      var angle = -(res.x*30).toFixed(1);
      if(angle>14){ angle=14; }
      else if(angle<-14){ angle=-14; }
      if(that.data.angle !== angle){
        that.setData({
          angle: angle
        });
      }
    });
  },
  getUserInfo: function (e) {
    app.getUserInfo(e.detail);
    var that = this;
    //请求登录
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true,
      loginCode: app.globalData.loginCode
    })

    if (this.data.hasUserInfo) {
      this.data.iv = e.detail.iv;
      this.data.encryptedData = e.detail.encryptedData;
      wx.showToast({
        title: '正在请求',
        icon: 'loading',
        duration: 10000
      });

      httpclient.req(
        'wx-user/getUserMessage',
        {
          apiName : 'jkum',
          iv : that.data.iv,
          encryptedData: that.data.encryptedData,
          code: that.data.loginCode
        },
        'GET',
        function(result){
          wx.hideToast();
          var resd = result.data;

          if(!resd.ok){
            wx.showModal({
              title: '请求失败',
              content: res.msg
            });
            return;
          }

          var data = JSON.parse(resd.data);
          that.setData({
            openId: data.openId,
            // unionId: data.unionId ? '' : data.unionId,
            nickname: data.nickName
          });

          that.goToIndex();
          app.saveOpenId(data);
        },
        function(fail){
          wx.hideToast();
          wx.showModal({
            title: '请求失败',
            content: fail.errMsg
          });
         
          wx.switchTab({
            url: '../start/start',
          })
        }
      );

    }else{
      wx.switchTab({
        url: '../start/start',
      })
    }
  }
});